<template>
    <el-dialog
            :title='$t("common.orderEdit")'
            :visible.sync="dialogVisible"
            :before-close="cancel"
            width="30%">
        <div id="orderEdit">
            <el-form ref="form" :model="form"  :rules="rules" label-width="80px" label-position="left"
                     :hide-required-asterisk="false">
                <el-form-item v-if="!formItemShow[key]"
                              v-for="item,key in form" :label="$t('order.'+key)" :prop="key">
                    <el-select v-if="addressOption[key]" v-model="form[key]" filterable
                               @change="addressData(key)"
                               :no-data-text	="$t('common.'+key+'NoDataTip')"
                               :placeholder="$t('common.selectPlaceholderTip')">
                        <el-option
                                v-for="item in addressOption[key]"
                                :key="item"
                                :label="item"
                                :value="item">
                        </el-option>
                    </el-select>
                    <el-select v-else-if="key==='orderState'" v-model="form[key]" :clearable="true"
                               @change="changeOrderState"
                               :placeholder="$t('common.selectPlaceholderTip')">
                        <el-option
                                v-for="item in orderState"
                                :key="item.value"
                                :label="$t('option.'+item.label).indexOf('.')>-1?item.label:$t('option.'+item.label)"
                                :disabled="item.value ===3"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <div v-else-if="key==='cancelReason'">
                        <el-select  v-model="form[key]"
                                   :placeholder="$t('common.selectPlaceholderTip')">
                            <el-option
                                    v-for="item in cancelReasonOption"
                                    :key="item.value"
                                    :label="$t('option.'+item.label).indexOf('.')>-1?item.label:$t('option.'+item.label)"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <el-input v-if="form.cancelReason === 3"  v-model="cancelReasonOther"  type="textarea" ></el-input>
                    </div>
                    <div v-else-if="key==='cancelReason1'">
                        <el-input  v-model="cancelReasonOther"  type="textarea" ></el-input>
                    </div>
                    <div v-else-if="key==='warehouseId'">
                        <el-select  v-model="form[key]"
                                   :placeholder="$t('common.selectPlaceholderTip')">
                            <el-option
                                    v-for="item in warehouseOptions"
                                    :key="item.value"
                                    :label="$t('option.'+item.label).indexOf('.')>-1?item.label:$t('option.'+item.label)"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div v-else-if="key === 'expressId'">
                        <el-input v-if="form[key]"  v-model="form[key]" :disabled="true" ></el-input>
                        <el-menu
                                v-if="!form[key]"
                                mode="horizontal"
                                @select="setExpressId">
                            <el-submenu index="create" >
                                <template slot="title">
                                    {{$t('common.create')}}
                                </template>
                                <el-submenu v-for="logistics in dropItem" :index="logistics.value">
                                    <template slot="title">{{logistics.label}}</template>
                                    <el-menu-item v-for="warehouse in warehouseOptions" :index="logistics.value+'-'+warehouse.value">{{warehouse.label}}</el-menu-item>
                                </el-submenu>
                            </el-submenu>
                        </el-menu>

                    </div>

                    <el-input v-else  v-model="form[key]" :disabled="key==='orderId'" :type="key==='addressDetail'?'textarea':'text'" ></el-input>


                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">{{$t('common.cancel')}}</el-button>
            <el-button type="primary" @click="confirm">{{$t('common.confirm')}}</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import {orderState,cancelReason} from '../../config/index'
    import {mapState} from 'vuex'
    export default {
        name: "orderEdit",
        props:{
            data:{
                type:Object,
                default(){
                    return {}
                }
            },
            changeRow: {
                type: Object,
                default(){
                    return {}
                }
            },
            refresh: {
                type: Boolean,
                default: false
            }
        },
        data(){
            let validatePhoneNumber = (rule, value, callback) => {
                let re = /(^['062','62','08','8','1'][0-9]{8,15})/
                if(!re.test(value)){
                    callback(new Error(this.$t('common.phoneValidTip')));
                } else {
                    callback();
                }
            };
            let validateProductNumber = (rule, value, callback) => {
                let re = /^[1-9]+[0-9]*$/
                if(!re.test(value)){
                    callback(new Error(this.$t('common.productFormatNumberValidTip')));
                } else {
                    callback();
                }
            };
            return{
                dialogVisible:false,
                orderState:orderState,
                cancelReasonOption:cancelReason,
                cancelReasonOther:'',
                addressOption:{
                    province:[],
                    city:[],
                    area:[],
                },
                form:{
                    orderId:'',
                    expressId:'',
                    price:'',
                    productNumber:'',
                    orderState:'',
                    cancelReason:'',
                    cancelReason1:'',
                    warehouseId:'',
                    userName:'',
                    phoneNumber:'',
                    contactTime:'',
                    zipCode:'',
                    province:'',
                    city:'',
                    area:'',
                    addressDetail:'',
                    userNotes:'',
                },
                dropItem:[{
                    label:this.$t('common.TianLongLogistics'),
                    value:1,
                },{
                    label:this.$t('common.JNELogistics'),
                    value:2,
                },{
                    label:this.$t('common.JXLogistics'),
                    value:3,
                },],
                otherKey:['productId','orderDetail'],
                rules:{
                    price:[{required: true, message: this.$t('common.priceValidTip'), trigger: 'blur'}],
                    province:[{required: true, message: this.$t('common.provinceValidTip'), trigger: 'blur'}],
                    city:[{required: true, message: this.$t('common.cityValidTip'), trigger: 'blur'}],
                    area:[{required: true, message: this.$t('common.areaValidTip'), trigger: 'blur'}],
                    productNumber:[{validator: validateProductNumber, trigger: 'blur'}],
                    addressDetail:[{required: true, message: this.$t('common.addressDetailValidTip'), trigger: 'blur'}],
                    userName:[{required: true, message: this.$t('common.userNameValidTip'), trigger: 'blur'}],
                    phoneNumber:[{validator: validatePhoneNumber, trigger: 'blur'}],

                }
            }
        },
        methods:{
            changeVisiable(){
                this.dialogVisible = !this.dialogVisible
            },
            initData(){
                for(let key of Object.keys(this.form)){
                    if(key === 'warehouseId' && this.data[key] === 0){
                        continue
                    }
                    this.form[key]=this.data[key]
                    if(key ==='cancelReason'){
                        this.cancelReasonOther = ''
                        if(typeof this.form[key] === 'string'){
                            let reason = this.form[key].split('---')
                            this.form[key] =isNaN(Number(reason[0]))?'':Number(reason[0])
                            this.cancelReasonOther = reason[1]
                        }
                    }
                }
                this.addressData('province',true)
                this.addressData('city',true)
                this.addressData('',true)
            },
            addressData(key,init){
                let params = {}
                if(key ==='province'){
                    params.province = this.form.province
                }else if(key ==='city'){
                    params.city = this.form.city
                }else if(key === 'area'){
                    return
                }
                this.$location(params).then(response=>{
                    if(response && response.code === 'success'){
                        if(key ==='province'){
                            this.addressOption.city =response.data
                            if(!init){
                                this.addressOption.area =[]
                                this.form.city = ''
                                this.form.area = ''
                            }
                        }else if(key ==='city'){
                            this.addressOption.area =response.data
                            if(!init){
                                this.form.area = ''
                            }
                        }else{
                            this.addressOption.province =response.data
                        }
                    }
                })
            },
            cancel(){
                this.$refs.form.clearValidate()
                this.$refs.form.resetFields()
                this.dialogVisible = false;
            },
            changeOrderState(v){
              if(v===3){
                  this.form.warehouseId = this.data.warehouseId
              }else{
                  this.form.warehouseId = ''
              }
            },
            confirm(){
                if(!this.beforeConfirmCheck()) return
                let otherKey = {}
                this.otherKey.forEach(v=>{
                    otherKey[v] = this.data[v]
                })
                let params = Object.assign({},this.form,otherKey)
                if(this.form.orderState === 2 || this.form.orderState === 8){
                    params.cancelReason =  this.cancelReasonOther?params.cancelReason+'---'+this.cancelReasonOther:params.cancelReason
                }else{
                    params.cancelReason = ''
                }
                if(!params.warehouseId) delete params.warehouseId
                this.$addOrder([params]).then(response=>{
                    if(response && response.code==='success'){
                        this.$message.success(this.$t('common.success'))
                        let changeRow = {_Id:'orderId'}
                        for(let key of Object.keys(this.form)){
                            changeRow[key]=params[key]
                        }
                        this.$emit("update:changeRow",changeRow)
                    }else{
                        this.$message.error(this.$t('common.error'))
                    }
                })
                this.$refs.form.clearValidate()
                this.dialogVisible = false;

            },
            handleCommand(type){
                this.setExpressId(type)
            },
            setExpressId(type){

                let params = {orderId:this.form.orderId,logisticsType:Number(type.split('-')[0]),warehouseId:Number(type.split('-')[1])}
                this.$setExpressId(params).then(response=>{
                    if(response && response.code ==='success'){
                        this.$message.success(this.$t('common.success'))
                        this.form.expressId = response.data[0] && response.data[0].expressId
                        this.form.orderState = 3
                        let changeRow = {_Id:'orderId'}
                        for(let key of Object.keys(this.form)){
                            if(key == 'orderId' || key == 'orderState'){
                                changeRow[key]=this.form[key]
                            }
                        }
                        this.$emit("update:changeRow",changeRow)
                    }else{
                        if(response && response.code ){
                            this.$message.error(this.$t('code.'+response.code))
                        }else{
                            this.$message.error(this.$t('common.error'))
                        }
                    }
                })
            },
            beforeConfirmCheck(){
                let valid = true;
                this.$refs.form.validate((v)=>{
                    valid = v
                })
                return valid
            }
        },
        computed:{
            ...mapState(['warehouseOptions', 'userInfo']),
            formItemShow(){
                let show = {}
                const {userType} = this.userInfo;
                show.cancelReason = this.form.orderState !== 2
                show.cancelReason1 = this.form.orderState !== 8
                show.warehouseId = this.form.orderState !== 3
                show.phoneNumber = userType === 2
                show.addressDetail = userType === 2
                return show
            }
        },
        mounted() {

        },
        watch:{
            dialogVisible(newV,oldV){
                if(newV){
                    this.initData()
                }
            }
        }
    }
</script>

<style>
    #orderEdit .el-menu--horizontal{
        border-bottom:none;
        height: 30px;
    }
    #orderEdit .el-menu--horizontal>.el-submenu .el-submenu__title{
        height: 30px;
        line-height: 30px;
    }
</style>